package com.lucaswangdev.web.controller;

import com.lucaswangdev.biz.request.user.UserCreateRequest;
import com.lucaswangdev.biz.request.user.UserDeleteRequest;
import com.lucaswangdev.biz.request.user.UserQueryRequest;
import com.lucaswangdev.biz.request.user.UserUpdateRequest;
import com.lucaswangdev.biz.response.common.PagingResponse;
import com.lucaswangdev.biz.service.UserService;
import com.lucaswangdev.model.convert.UserConverter;
import com.lucaswangdev.model.dto.UserDTO;
import com.lucaswangdev.web.BaseResult;
import com.lucaswangdev.web.vo.UserVO;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @RequestMapping(value = "/insert", method = RequestMethod.POST)
    public BaseResult<Void> insert(@RequestBody UserCreateRequest request){
        Boolean success = userService.create(request);
        if(success == null || !success) {
            return BaseResult.systemFail();
        }
        return BaseResult.success();
    }

    @RequestMapping(value = "/list-page", method = RequestMethod.POST)
    public BaseResult<PagingResponse<UserVO>> listPage(@RequestBody UserQueryRequest request){
        PagingResponse<UserDTO> response = userService.listPage(request);
        if(response == null) {
            return BaseResult.systemFail();
        }
        if(response.isSuccess()){
            List<UserVO> vos = UserConverter.INSTANCE.convertDTOList2VOList(response.getTableData());
            PagingResponse<UserVO> result = PagingResponse.build(vos, response.getPaging());
            return BaseResult.success(result);
        } else {
            return BaseResult.bizFail(response.getErrorMsg());
        }
    }

    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult<Void> update(@RequestBody UserUpdateRequest request){
        Boolean success = userService.modified(request);
        if(success == null || !success) {
            return BaseResult.systemFail();
        }
        return BaseResult.success();
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public BaseResult<Void> delete(@RequestBody UserDeleteRequest request){
        Boolean success = userService.deleteById(request);
        if(success == null || !success) {
            return BaseResult.systemFail();
        }
        return BaseResult.success();
    }
}
